//
//  StatusPictureView.swift
//  WeiBo09
//
//  Created by 裘明 on 15/9/13.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit
import SDWebImage
private let StatusPictureViewCellID = "StatusPictureViewCellID"

///  配图
class StatusPictureView: UICollectionView {
    
    var statusViewModel: StatusViewModel?  {
        didSet {
            // 当调用了sizeToFit的时候，系统会自动调用sizeThatFits
            sizeToFit()
            // 刷新数据

            reloadData()
        }
        
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
       return calcViewSize()
    }
    
    private func calcViewSize() -> CGSize {
        // 准备工作
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置itemSize的默认大小
        layout.itemSize = CGSize(width: statusPictureItemWidth, height: statusPictureItemWidth)
        // 计算item的个数
        let count = statusViewModel?.thumbnailUrl?.count ?? 0
        
        // 没图
        if count == 0 {
            return CGSizeZero
        }
        
        // 当只有一张图片的时候
        if count == 1 {
            var size = CGSize(width: 150, height: 150)
            
            let key = statusViewModel?.thumbnailUrl![0].absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                size = image.size
            }
            // 单独处理过宽或过窄的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            
            layout.itemSize = size
            return size
        }
        // 有四张图片的时候
        if count == 4 {
            let w = statusPictureItemWidth * 2 + statusPictureItemMargin
            return CGSize(width: w, height: w)
        }
        
        // 当只有2、3、5、6、7、8、9
        let row = CGFloat((count - 1) / Int(statusCellPictureMaxCount) + 1)
        let h = row * statusPictureItemWidth + (row - 1) * statusPictureItemMargin
        return CGSize(width:statusCellPictureMaxWidth, height: h)
        
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = statusPictureItemMargin
        layout.minimumLineSpacing = statusPictureItemMargin
        backgroundColor = UIColor(white: 0.98, alpha: 1.0)
        dataSource = self
        // 注册可重用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

 /// 数据源方法
extension StatusPictureView: UICollectionViewDataSource {
   
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (statusViewModel?.thumbnailUrl?.count) ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        // 1.在缓存池中找可重用cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        // 2.给cell赋值
        cell.imageUrl = statusViewModel!.thumbnailUrl![indexPath.item]
        
        // 3.返回cell
        return cell
    }
    
}

/// 配图视图cell
private class StatusPictureViewCell: UICollectionViewCell {
    
    var imageUrl: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageUrl)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 1.添加控件
        contentView.addSubview(iconView)
        // 2.设置布局
        iconView.ff_Fill(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        iv.layer.cornerRadius = 10
        iv.layer.masksToBounds = true
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
}
